Set encrypted swap in your linux

You can encrypt your swap partition with ephemeral key that is generated during boot time and destroyed when computer is shut down.

!DANGER!

Setting swap this way will disable system hibernation, as during hibernation ram contents are stored in the swap partition.

Setting this up is quite easy, but i found small errors in some guides (or these guides were for older versions debian/dm-crypt/etc).

So anyway here is what worked on buster.

  1. Find UUID of your swap partition, eg. by looking at fstab:

    UUID=12312d-312dah-...  none swap sw 0 0
    

    if your fstab has no swap configured, you might find your partition name using blkid command (that prints all ids for all partitions)

  2. Set up /etc/crypttab, add a line that looks like that:

    cswap UUID=12312d-312dah-... /dev/urandom swap,cipher=aes-cbc-essiv:sha256,size=256
    

    Full syntax of this file is explained in man crypttab, but here is the gist of it:

    • cswap --- is a name for newly created device
    • UUID= --- locates partition for swap
    • /dev/urandom --- is the key for swap (/dev/urandom produces random cryptographically save byte sequence.
    • swap,cipher=aes-cbc-essiv:sha256,size=256 --- cryptsetup options, in this case: format as swap, use default cipher and default key size.
  3. Edit fstab to use encrypted swap file:

    /dev/mapper/cswap  none swap sw 0 0
    

    here just replace first column (that contained UUID=...) with /dev/mapper/cswap.

  4. Test everything works locally:

    swapoff -a # disables swap
    cryptdisks_start cswap # starts cryptmapper
    swapon -a # starts all swap partitions
    cat /proc/swaps # verify you have swap enabled